package com.lazyframework.security.web.configuration.configurer;

import com.lazyframework.security.web.JwtClients;
import com.lazyframework.security.web.authentication.AuthenticationManager;
import com.lazyframework.security.web.authentication.UserDetailsService;
import com.lazyframework.security.web.authentication.filter.UsernamePasswordAuthenticationFilter;
import com.lazyframework.security.web.authentication.provider.DaoAuthenticationProvider;
import com.lazyframework.security.web.configuration.HttpSecurity;
import com.lazyframework.security.web.configuration.SecurityConfigurerAdapter;
import com.lazyframework.security.web.util.PasswordEncoder;

import javax.servlet.Filter;

/**
 * Create by lazy in 2019/11/12
 */
public class FormLoginConfigurer extends SecurityConfigurerAdapter<Filter, HttpSecurity> {

    private JwtClients jwtClients;

    private PasswordEncoder passwordEncoder;

    private UserDetailsService userDetailsService;

    public FormLoginConfigurer jwtClients(JwtClients jwtClients) {
        this.jwtClients = jwtClients;
        return this;
    }

    public FormLoginConfigurer passwordEncoder(PasswordEncoder passwordEncoder) {
        this.passwordEncoder = passwordEncoder;
        return this;
    }

    public FormLoginConfigurer userDetailsService(UserDetailsService userDetailsService) {
        this.userDetailsService = userDetailsService;
        return this;
    }

    @Override
    public void configure(HttpSecurity http) {
        DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
        provider.setPasswordEncoder(passwordEncoder);
        provider.setUserDetailsService(userDetailsService);

        AuthenticationManager authenticationManager = http.authenticationManager();
        authenticationManager.registerProvider(provider);

        UsernamePasswordAuthenticationFilter filter = new UsernamePasswordAuthenticationFilter();
        filter.setJwtClients(jwtClients);
        filter.setAuthenticationManager(authenticationManager);

        http.addFilter(filter);
    }

}
